package com.jeecg.demo.controller;

import com.jeecg.demo.entity.OrderdjEntity;
import com.jeecg.demo.entity.TradeorderEntity;
import com.jeecg.demo.entity.TraderStatistics;
import com.jeecg.demo.entity.VEcpTradeorderEntity;
import com.jeecg.demo.service.OrderdjServiceI;
import com.jeecg.demo.service.TradeorderServiceI;
import com.jeecg.demo.service.VEcpTradeorderServiceI;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Title: Controller
 * @Description: 成交
 * @author onlineGenerator
 * @date 2018-11-20 08:34:36
 * @version V1.0
 *
 */
@Controller
@RequestMapping("/vEcpTradeorderController")
public class VEcpTradeorderController extends BaseController {
    private static final Logger logger = LoggerFactory
            .getLogger(VEcpTradeorderController.class);

    @Autowired
    private VEcpTradeorderServiceI vEcpTradeorderService;
    @Autowired
    private SystemService systemService;
    @Autowired
    private TradeorderServiceI tradeorderService;
    @Autowired
    private OrderdjServiceI orderdjService;

    /**
     * 成交列表 页面跳转
     *
     * @return
     */
    @RequestMapping(params = "list")
    public ModelAndView list(HttpServletRequest request, String type) {
        request.setAttribute("type", type);
        return new ModelAndView("com/jeecg/vEcpTradeorder/vEcpTradeorderList");
    }

    //成交报表
    @RequestMapping(params = "transcationstatment")
    public ModelAndView vEcpTradeorderController(HttpServletRequest request){
        String ztmc = request.getParameter("ztmc") == null ?"":request.getParameter("ztmc");
        String beginTime = request.getParameter("beginTime") == null ?"":request.getParameter("beginTime");
        String endTime = request.getParameter("endTime") == null ? "" : request.getParameter("endTime");
        List<TraderStatistics> traderStatisticsList = tradeorderService.getTraderStatisticsList(ztmc,beginTime,endTime);
        return new ModelAndView("com/jeecg/vEcpTradeorder/TraderStatmentList");
    }

    /**
     * easyui AJAX请求数据
     *
     * @param request
     * @param response
     * @param dataGrid
     * @param user
     * @throws Exception
     */

    @RequestMapping(params = "datagrid")
    public void datagrid(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, String type) throws Exception {
        CriteriaQuery cq = new CriteriaQuery(VEcpTradeorderEntity.class,
                dataGrid);
        // 查询条件组装器
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                vEcpTradeorder, request.getParameterMap());
        String ctBegin = request.getParameter("createTime_begin");
        String ctEnd = request.getParameter("createTime_end");
        if (StringUtil.isNotEmpty(ctBegin) && StringUtil.isNotEmpty(ctEnd)) {
            try {
                // 自定义追加查询条件
                cq.ge("createTime", new SimpleDateFormat("yyyy-MM-dd")
                        .parse(ctBegin));
                cq.le("createTime", new SimpleDateFormat("yyyy-MM-dd")
                        .parse(ctEnd));
            }
            catch (Exception e) {
                throw new BusinessException(e.getMessage());
            }
            cq.add();
        }
        this.vEcpTradeorderService.getDataGridReturn(cq, true);

    if ("query".equals(type)) {
    	// datagrid标签没有封装合计功能
    	String total = String.valueOf(vEcpTradeorderService.findOneForJdbc(
    			"select sum(TOQUALITY) as ssum from  V_ECP_TRADEORDER").get(
    					"ssum"));
    	String price = String.valueOf(vEcpTradeorderService.findOneForJdbc(
    			"select sum(toprice) as price from  V_ECP_TRADEORDER").get(
    					"price"));
    	/*
    	 * 说明：格式为 字段名:值(可选，不写该值时为分页数据的合计) 多个合计 以 , 分割
    	 */
    	// datagrid标签没有封装合计功能
        String unit = "千克";
        String unit1 = "元";
        Double tt = Double.valueOf(total);
        Double pp = Double.valueOf(price);
        Double tp = tt * pp;
        if (tt >= 1000) {
            unit = "吨";
            tt = tt / 1000;
        }
        DecimalFormat df = new DecimalFormat("#.##");
            if (tp >= 10000 & tp < 100000000) {
                unit1 = "万元";
                tp = tp / 10000;
            }
            if (tp >= 100000000) {
                unit1 = "亿";
                tp = tp / 100000000;
            }
            dataGrid.setFooter("toquality:" + df.format(tt) + unit
                    + ",age,toprice:合计,varietyname:" + df.format(tp) + unit1
                    + ",age,commodityname:" + "总金额");
        }

        TagUtil.datagrid(response, dataGrid);
    }

    /**
     * 删除成交
     *
     * @return
     */
    @RequestMapping(params = "doDel")
    @ResponseBody
    public AjaxJson doDel(VEcpTradeorderEntity vEcpTradeorder, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        vEcpTradeorder = systemService.getEntity(VEcpTradeorderEntity.class, vEcpTradeorder.getId());
        message = "删除成功";
        try {
            vEcpTradeorderService.delete(vEcpTradeorder);
            systemService.addLog(message, Globals.Log_Type_DEL,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 批量删除成交
     *
     * @return
     */
    @RequestMapping(params = "doBatchDel")
    @ResponseBody
    public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "删除成功";
        try {
            for (String id : ids.split(",")) {
                VEcpTradeorderEntity vEcpTradeorder = systemService.getEntity(
                        VEcpTradeorderEntity.class, Integer.parseInt(id));
                vEcpTradeorderService.delete(vEcpTradeorder);
                systemService.addLog(message, Globals.Log_Type_DEL,
                        Globals.Log_Leavel_INFO);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "删除失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 添加成交
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doAdd")
    @ResponseBody
    public AjaxJson doAdd(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "添加成功";
        try {
            vEcpTradeorderService.save(vEcpTradeorder);
            systemService.addLog(message, Globals.Log_Type_INSERT,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "添加失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 更新成交
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doUpdate")
    @ResponseBody
    public AjaxJson doUpdate(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "更新成功";
        VEcpTradeorderEntity t = vEcpTradeorderService.get(
                VEcpTradeorderEntity.class, vEcpTradeorder.getId());
        try {
            MyBeanUtils.copyBeanNotNull2Bean(vEcpTradeorder, t);
            vEcpTradeorderService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE,
                    Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "更新失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * 审核TRADEORDER
     *
     * @param ids
     * @return
     */
    @RequestMapping(params = "doCancel")
    @ResponseBody
    public AjaxJson doCancel(TradeorderEntity tradeorder, HttpServletRequest request) {
        String message = null;
        AjaxJson j = new AjaxJson();
        message = "撤销成功";
        // VEcpTradeorderEntity t =
        // vEcpTradeorderService.get(VEcpTradeorderEntity.class,
        // vEcpTradeorder.getId());
        TradeorderEntity t = systemService.getEntity(TradeorderEntity.class,tradeorder.getId());
        try {
            t.setTostatus("0");
            tradeorderService.saveOrUpdate(t);
            systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
        }
        catch (Exception e) {
            e.printStackTrace();
            message = "撤销失败";
            throw new BusinessException(e.getMessage());
        }
        j.setMsg(message);
        return j;
    }

    /**
     * TRADEORDER撤销
     *
     * @return
     */
    @RequestMapping(params = "goCancel")
    public ModelAndView goCancel(VEcpTradeorderEntity vEcpTradeorder, HttpServletRequest req) {
        if (StringUtil.isNotEmpty(vEcpTradeorder.getId())) {
            vEcpTradeorder = vEcpTradeorderService.getEntity(VEcpTradeorderEntity.class, vEcpTradeorder.getId());
            req.setAttribute("action", "vEcpTradeorderController.do?doCancel");
            req.setAttribute("vEcpTradeorderPage", vEcpTradeorder);
        }
        return new ModelAndView("com/jeecg/vEcpTradeorder/vEcpTradeorder-update");
    }

    /**
     * 成交新增页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goAdd")
    public ModelAndView goAdd(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest req) {
        if (StringUtil.isNotEmpty(vEcpTradeorder.getId())) {
            vEcpTradeorder = vEcpTradeorderService.getEntity(
                    VEcpTradeorderEntity.class, vEcpTradeorder.getId());
            req.setAttribute("vEcpTradeorderPage", vEcpTradeorder);
        }
        return new ModelAndView("com/jeecg/vEcpTradeorder/vEcpTradeorder-add");
    }

    /**
     * 成交编辑页面跳转
     *
     * @return
     */
    @RequestMapping(params = "goUpdate")
    public ModelAndView goUpdate(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest req) {
        List<OrderdjEntity> listorderdj = null;
        if (StringUtil.isNotEmpty(vEcpTradeorder.getId())) {
            vEcpTradeorder = vEcpTradeorderService.getEntity(
                    VEcpTradeorderEntity.class, vEcpTradeorder.getId());
            req.setAttribute("vEcpTradeorderPage", vEcpTradeorder);
            /*listorderdj = orderdjService.findByProperty(OrderdjEntity.class,
                    "pid", vEcpTradeorder.getId());*/
        }
        req.setAttribute("listorderdj", listorderdj);
        return new ModelAndView("com/jeecg/vEcpTradeorder/vEcpTradeorder-update");
    }

    /**
     * 导入功能跳转
     *
     * @return
     */
    @RequestMapping(params = "upload")
    public ModelAndView upload(HttpServletRequest req) {
        req.setAttribute("controller_name", "vEcpTradeorderController");
        return new ModelAndView("common/upload/pub_excel_upload");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXls")
    public String exportXls(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap) {
        CriteriaQuery cq = new CriteriaQuery(VEcpTradeorderEntity.class,
                dataGrid);
        org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
                vEcpTradeorder, request.getParameterMap());
        List<VEcpTradeorderEntity> vEcpTradeorders = this.vEcpTradeorderService
                .getListByCriteriaQuery(cq, false);
        modelMap.put(NormalExcelConstants.FILE_NAME, "成交");
        modelMap.put(NormalExcelConstants.CLASS, VEcpTradeorderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("成交列表",
                "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, vEcpTradeorders);
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    /**
     * 导出excel 使模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(params = "exportXlsByT")
    public String exportXlsByT(VEcpTradeorderEntity vEcpTradeorder,
            HttpServletRequest request, HttpServletResponse response,
            DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "成交");
        modelMap.put(NormalExcelConstants.CLASS, VEcpTradeorderEntity.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("成交列表",
                "导出人:" + ResourceUtil.getSessionUser().getRealName(), "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, new ArrayList());
        return NormalExcelConstants.JEECG_EXCEL_VIEW;
    }

    @SuppressWarnings("unchecked")
    @RequestMapping(params = "importExcel", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson importExcel(HttpServletRequest request,
            HttpServletResponse response) {
        AjaxJson j = new AjaxJson();

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<VEcpTradeorderEntity> listVEcpTradeorderEntitys = ExcelImportUtil
                        .importExcel(file.getInputStream(),
                                VEcpTradeorderEntity.class, params);
                for (VEcpTradeorderEntity vEcpTradeorder : listVEcpTradeorderEntitys) {
                    vEcpTradeorderService.save(vEcpTradeorder);
                }
                j.setMsg("文件导入成功！");
            }
            catch (Exception e) {
                j.setMsg("文件导入失败！");
                logger.error(e.getMessage());
            }
            finally {
                try {
                    file.getInputStream().close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return j;
    }

}
